<?php
declare (strict_types = 1);

namespace app\wx\controller;

use app\BaseController;
use think\facade\Env;
use think\facade\Log;



class Index extends BaseController
{
   
    public function index()
    {
        $data=['game'=>'wx方法'
    
        ];
        return json($data);
    }

    public function GetOpenId($appid,$secret,$js_code){
        $data=[
            'appid'=>$appid,
            'secret'=>$secret,
            'js_code'=>$js_code,
            'grant_type'=>'authorization_code',
        ];

        $url = 'https://api.weixin.qq.com/sns/jscode2session'; // 替换为你需要访问的URL
        //$url = 'https://www.baidu.com/'; // 替换为你需要访问的URL
        $options = array(
            'http' => array(
                'header'  => "Content-type: application/x-www-form-urlencoded\r\n",
                'method'  => 'POST',
                'content' => http_build_query($data)
            )
        );
        $context  = stream_context_create($options);
        $result = file_get_contents($url, false, $context);


        $fromServer = json_decode($result, true); 


        //dump($fromServer);

        // if(!empty($fromServer["session_key"])){

        // }
        $session = $fromServer["session_key"];
        $openId = $fromServer["openid"];
        // $openId = $fromServer["openid"];
 
        $res = [];
        $r = false;

        if (!empty($fromServer["session_key"])) {
            // 处理获取到的数据
            $res['session_key'] = $fromServer["session_key"];
            $r = true;
        }

        if (!empty($fromServer["openid"])) {
            $res['openid'] = $fromServer["openid"];
            $r = true;
        }

        if (!empty($fromServer["errcode"])) {
            $res['errcode'] = $fromServer["errcode"];
            $r = false;
        }
        if (!empty($fromServer["errmsg"])) {
            $res['errmsg'] = $fromServer["errmsg"];
            $r = false;
        }

        $res['Result'] = $r;

        return json($res);
    }
}